<template>
  <span>The example demonstrates how to convert Word to PDF.</span>
  <button @click="startProcessing">读取RTF文档</button>
  <a v-if="downloadUrl" :href="downloadUrl" :download="downloadName">
    Click here to download the generated file
  </a>
  <div :style="{ border: '1px solid gray' }">
    <h3  v-if="outputRefStr">输出内容：</h3>
    <div ref="outputRef"></div>
  </div>
</template>

<script setup>
import { ref, onMounted  } from "vue";
// import { rtfArrayBufferToHtmlStr } from "../utils";
import * as shiva from 'shiva-wasm';

const rtfArrayBufferToHtmlStr = async (ab) => {

  await shiva.default('/shiva_wasm_bg.wasm');

  // await shiva.initSync();

  const data = shiva.convert(ab, shiva.FileFormat.Rtf, shiva.FileFormat.Docx);

  const blob = new Blob([data], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
    const blobURL = window.URL.createObjectURL(blob);
    const fileName = 'save.docx';
    const tempLink = document.createElement('a');
    tempLink.style.display = 'none';
    tempLink.href = blobURL;
    const downloadName = decodeURIComponent(fileName);
    tempLink.setAttribute('download', downloadName);
    tempLink.download = downloadName;
    // alert(decodeURIComponent(fileName));
    // 兼容：某些浏览器不支持HTML5的download属性
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank');
    }
    // 挂载a标签
    document.body.appendChild(tempLink);
    tempLink.click();
    setTimeout(() => {
      document.body.removeChild(tempLink);
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL);
    }, 3000);

  // var decoder = new TextDecoder("utf-8");
  // const htmlStr = decoder.decode(dataStr);

  // return htmlStr;
};

const downloadUrl = ref(null);
const downloadName = ref("");
const outputRef = ref(null);
const outputHtmlStr = ref(null);

const importRtfFileToString = async () => {
    return new Promise((resolve, reject) => {
        // let rtfTextContent = '';
        // 创建 input 元素
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.rtf';
        let isOpenFile = false;
        // 监听文件选择事件
        input.onchange = async (event) => {
            const file = event.target.files[0];
            if (file) {
                isOpenFile = true;
                // 读取文件内容
                const reader = new FileReader();
                reader.onload = (e) => {
                    const ab = e.target.result;
                    // 当文件读取完成后，调用 resolve 函数将结果传递出去
                    resolve({
                      name: file.name,
                      arrayBuffer: new Uint8Array(ab)
                    });
                };
                reader.onerror = (error) => {
                    // 如果文件读取出现错误，调用 reject 函数
                    reject(error);
                };
                reader.readAsArrayBuffer(file);
            }
        };
        // 取消事件
        window.addEventListener(
            'focus',
            () => {
                setTimeout(() => {
                    if (!isOpenFile) {
                        // 取消逻辑处理
                        reject(new Error('User cancelled file selection'));
                    }
                }, 300);
            },
            { once: true }
        );

        // 触发文件选择对话框
        input.click();
    });
};

    const startProcessing = async () => {
      try {


        const importFile = await importRtfFileToString();
          const htmlStr = await rtfArrayBufferToHtmlStr(importFile.arrayBuffer);

          outputHtmlStr.value = !!htmlStr;
          outputRef.value.innerHTML=htmlStr;

        
      } catch (error) {
        console.error("Error processing the document:", error);
      }
    };
</script>